﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using QMSDAL;

namespace QuaManSys.CusSatiSur
{

    public partial class CusSatiSurAuditing : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["id"] == null) Response.Redirect("MainPage.aspx");
            lblInfomationId.Text = Request["id"].ToString();
            if (!IsPostBack)
            {
                initPageInfo();
                initAttatchment();
            }
        }

        /// <summary>
        /// 初始化满意度
        /// </summary>
        private void initRatioButton(RadioButton rbtn1, RadioButton rbtn2,
            RadioButton rbtn3, RadioButton rbtn4, string match)
        {
            rbtn1.Checked = rbtn1.Text.Equals(match) ? true : false;
            rbtn2.Checked = rbtn2.Text.Equals(match) ? true : false;
            rbtn3.Checked = rbtn3.Text.Equals(match) ? true : false;
            rbtn4.Checked = rbtn4.Text.Equals(match) ? true : false;
        }

        string[] customsClass = new string[]{"船厂物资部","船厂设计部", "船厂质量部&船东建造组"
        , "船厂生产部门", "船东机务部门", "所有顾客"};

        private void initPageInfo()
        {
            int selectNum = Convert.ToInt16(lblInfomationId.Text.Substring(2, 2));
            lblClass.Text = customsClass[selectNum - 1];
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                var db = from d in context.CusSatSur
                         where d.infomationId.Equals(lblInfomationId.Text)
                         select d;
                tbxCustomName.Text = db.Single().customName;
                tbxDepartment.Text = db.Single().contactNum;
                tbxVisitDate.Text = db.Single().visitDate.ToString().Split(' ')[0].Replace('-', '/');
                rbtInterview.Checked = rbtInterview.Text.Equals(db.Single().visitedForm.ToString()) ? true : false;
                rbtFax.Checked = rbtInterview.Text.Equals(db.Single().visitedForm.ToString()) ? false : true;
                tbxExpectTime.Text = db.Single().expectTime.ToString().Split(' ')[0].Replace('-', '/');
                tbxContactMan.Text = db.Single().contactMan;
                tbxContactNum.Text = db.Single().contactNum;

                initRatioButton(Jhenmanyi, Jmanyi, Jyiban, Jbumanyi, db.Single().satJiaohuoqi.ToString());
                initRatioButton(Whenmanyi, Wmanyi, Wyiban, Wbumanyi, db.Single().satWanzheng.ToString());
                initRatioButton(Thenmanyi, Tmanyi, Tyiban, Tbumanyi, db.Single().satJiaohuojihua.ToString());
                initRatioButton(TXhenmanyi, TXmanyi, TXyiban, TXbumanyi, db.Single().satTongxin.ToString());
                initRatioButton(Chenmanyi, Cmanyi, Cyiban, Cbumanyi, db.Single().satChulisudu.ToString());
                initRatioButton(JGhenmanyi, JGmanyi, JGyiban, JGbumanyi, db.Single().satJieguomanyi.ToString());

                txaInstruction.InnerText = db.Single().instruction.ToString();
                txaToBeImproved.InnerText = db.Single().toBeImproved.ToString();
                txaOurAdvantage.InnerText = db.Single().ourAdvantage.ToString();
                txaSuggestion.InnerText = db.Single().suggestion.ToString();
                tbxVisitedCustmer.Text = db.Single().visitedCustom.ToString();
                tbxVisitedDate.Text = db.Single().visitDate.ToString().Split(' ')[0].Replace('-', '/');
                tbxCustomTele.Text = db.Single().cuntomTele.ToString();

            }
        }

        protected void initAttatchment()
        {
            string path = "~/FileUploadCS/" + lblInfomationId.Text + "/";
            string phyPath = HttpContext.Current.Request.MapPath(path);
            DirectoryInfo upDir = new DirectoryInfo(phyPath);
            if (!upDir.Exists)
            {
                return;
            }
            FileInfo[] fileInfo = upDir.GetFiles();
            attatch.DataSource = fileInfo;
            attatch.DataBind();

        }
        /// <summary>
        /// 文件上传下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnItemCommand(object sender, RepeaterCommandEventArgs e)
        {

            string path = "~/FileUploadCS/" + lblInfomationId.Text + "/" + e.CommandArgument;
            string phyPath = HttpContext.Current.Request.MapPath(path);
            if (e.CommandName == "delete")
            {
                FileInfo file = new System.IO.FileInfo(phyPath);
                if (file.Exists)
                {
                    file.Delete();
                    foreach (RepeaterItem item in attatch.Items)
                    {
                        TextBox tb = (TextBox)item.FindControl("attatchName");
                        if (tb.Text == e.CommandArgument.ToString())
                        {
                            tb.Visible = false;
                            Button btn1 = (Button)item.FindControl("d1");
                            Button btn2 = (Button)item.FindControl("d2");
                            btn1.Visible = false;
                            btn2.Visible = false;
                        }
                    }
                }

            }
            else if (e.CommandName == "download")
            {
                FileInfo file = new System.IO.FileInfo(phyPath);
                Page.Response.Buffer = false;
                Page.Response.Charset = "UTF-8";
                Page.Response.AppendHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode((file.Name)));
                Page.Response.HeaderEncoding = System.Text.Encoding.UTF8;
                Page.Response.ContentEncoding = System.Text.Encoding.UTF8;//GetEncoding("UTF-8");
                Page.Response.ContentType = "application/ms-excel";
                Page.Response.WriteFile(file.FullName);
                //System.IO.File.Delete(file.FullName);
                Page.Response.End();
            }

        }

        /// <summary>
        /// 返回ratioButton的Text
        /// </summary>
        private string insertRatioButton(RadioButton rbtn1, RadioButton rbtn2,
            RadioButton rbtn3, RadioButton rbtn4)
        {
            if (rbtn1.Checked) return "很满意";
            if (rbtn2.Checked) return "满意";
            if (rbtn3.Checked) return "一般";
            if (rbtn4.Checked) return "不满意";
            return null;

        }

        protected void submitInfomation()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                var db = from b in context.CusSatSur
                         where b.infomationId.Equals(lblInfomationId.Text)
                         select b;

                db.Single().customName = tbxCustomName.Text;
                db.Single().contactNum = tbxDepartment.Text;
                db.Single().visitDate = Convert.ToDateTime(tbxVisitDate.Text);
                db.Single().visitedForm = rbtInterview.Checked ? rbtInterview.Text : rbtFax.Text;
                db.Single().expectTime = Convert.ToDateTime(tbxExpectTime.Text);

                db.Single().contactMan = tbxContactMan.Text;
                db.Single().contactNum = tbxContactNum.Text;

                db.Single().satJiaohuoqi = insertRatioButton(Jhenmanyi, Jmanyi, Jyiban, Jbumanyi);
                db.Single().satWanzheng = insertRatioButton(Whenmanyi, Wmanyi, Wyiban, Wbumanyi);
                db.Single().satJiaohuojihua = insertRatioButton(Thenmanyi, Tmanyi, Tyiban, Tbumanyi);
                db.Single().satTongxin = insertRatioButton(TXhenmanyi, TXmanyi, TXyiban, TXbumanyi);
                db.Single().satChulisudu = insertRatioButton(Chenmanyi, Cmanyi, Cyiban, Cbumanyi);
                db.Single().satJieguomanyi = insertRatioButton(JGhenmanyi, JGmanyi, JGyiban, JGbumanyi);

                db.Single().instruction = txaInstruction.InnerText;
                db.Single().toBeImproved = txaToBeImproved.InnerText;
                db.Single().ourAdvantage = txaOurAdvantage.InnerText;
                db.Single().suggestion = txaSuggestion.InnerText;
                db.Single().visitedCustom = tbxVisitedCustmer.Text;
                db.Single().visitDate = Convert.ToDateTime(tbxVisitedDate.Text);
                db.Single().cuntomTele = tbxCustomTele.Text;

                db.Single().processStatus = "收集";
                context.SaveChanges();

                CurUser user = (CurUser)Session["CurUser"];
                Common.CusSatSurRelatedDeptOperation.AddCurSatSurRelatedDept(lblInfomationId.Text, user.department);
            }

        }

        #region 文件上传
        protected void fileUpload()
        {
            #region
            int cnt = Convert.ToInt16(hidden.Value.ToString());
            HtmlInputFile f = this.FileUploadD1;
            UpLoadFile(f.PostedFile);

            for (int i = 2; i <= cnt; i++)
            {
                HttpPostedFile f1 = Request.Files["FileUploadD" + i];
                UpLoadFile(f1);
            }
            #endregion

        }

        /// <summary>
        /// 文件上传。
        /// </summary>
        /// <param name="InputFile"></param>
        /// <param name="Path"></param>
        public string UpLoadFile(HttpPostedFile InputFile)
        {

            //判断有控件内容进入
            string b = "";
            string xdd = "";
            try
            {
                xdd = InputFile.FileName.ToString();//获取上传文件的名字
            }
            catch (Exception e)
            {
                return xdd;
            }
            if (xdd != "")
            {
                string path = "~/FileUploadCS/" + lblInfomationId.Text + "/";

                string PRICE_FJ_FJMC = "";
                string PRICE_FJ_FJHZ = "";
                string PRICE_FJ_PATH_SC = "";
                string PRICE_FJ_PATH_XZ = "";

                PRICE_FJ_PATH_XZ = path;
                //上传全路径包括文件名G:\\新建文件夹 (4)\\新建 文本文档.txt
                PRICE_FJ_PATH_SC = InputFile.FileName;
                //文件名包括后缀 新建 文本文档.txt"
                PRICE_FJ_FJMC = PRICE_FJ_PATH_SC.Substring(PRICE_FJ_PATH_SC.LastIndexOf("\\") + 1);
                ////
                //建立上传对象
                //
                HttpPostedFile postedFile = InputFile;
                //文件名包括后缀 新建 文本文档.txt"
                string fileName = System.IO.Path.GetFileName(postedFile.FileName);
                //文件后缀
                PRICE_FJ_FJHZ = System.IO.Path.GetExtension(fileName);


                string phyPath = HttpContext.Current.Request.MapPath(PRICE_FJ_PATH_XZ);//获取文件所在根目录
                //判断路径是否存在,若不存在则创建路径
                DirectoryInfo upDir = new DirectoryInfo(phyPath);
                if (!upDir.Exists)
                {
                    upDir.Create();
                }
                //
                //保存文件
                //
                try
                {
                    postedFile.SaveAs(phyPath + PRICE_FJ_FJMC);//文件保存
                    return b = phyPath;

                }
                catch
                {
                    throw new ApplicationException("上传失败!");
                }
                //返回上传文件的信息
            }

            return b;
        }

        #endregion

        protected void submit_Click(object sender, EventArgs e)
        {
            //从session中取出当前用户信息并显示
            CurUser user = (CurUser)Session["CurUser"];
            //判断当前用户是否具有归档权限
            bool roleAccess = Permission.JudgePermission(user, "3B", "C0");
            if (roleAccess)
            {
                fileUpload();
                submitInfomation();
                Response.Redirect("success.aspx");
            }
        }

        protected void rtnRollback_Click(object sender, EventArgs e)
        {
            //从session中取出当前用户信息并显示
            CurUser user = (CurUser)Session["CurUser"];
            //判断当前用户是否具有归档权限
            bool roleAccess = Permission.JudgePermission(user, "3B", "B2");
            if (roleAccess)
            {
                fileUpload();
                using (QuaManSysEntities context = new QuaManSysEntities())
                {
                    var db = from b in context.CusSatSur
                             where b.infomationId.Equals(lblInfomationId.Text)
                             select b;
                    db.Single().processStatus = "汇总";
                    context.SaveChanges();
                }
                Response.Redirect("success.aspx");
            }

        }
    }
}